package dao

import (
	"fmt"
	"goWeb/bookStore/model"
	"goWeb/bookStore/utils"
)

func AddCart(ct *model.Cart) (err error) {
	sqlstr := "insert into cart(id,tcount,tamout,user_id) values(?,?,?,?)"
	//	fmt.Printf("添加Cart的时候，参数分别为%v %v %v %v \n", ct.Id, ct.GetTcount(), ct.GetTamout(), ct.Userid)
	_, err = utils.Db.Exec(sqlstr, ct.Id, ct.GetTcount(), ct.GetTamout(), ct.Userid)
	if err != nil {
		fmt.Println("添加cart失败", err)
	}
	for _, v := range ct.CartItems {
		AddCartItem(v)
	}
	return

}

//根据userid来获取cart信息
func GetCartByUserId(Userid int) (cart *model.Cart, err error) {
	sqlstr := "select id,tcount,tamout,user_id from cart where user_id=?"
	row := utils.Db.QueryRow(sqlstr, Userid)
	cart = &model.Cart{}
	err = row.Scan(&cart.Id, &cart.Tcount, &cart.Tamout, &cart.Userid)
	if err != nil {
		return nil, err
	}
	cis, err := GetCartItemByCartId(cart.Id)
	cart.CartItems = cis
	return cart, err
}

//更新Cart
func UpdateCart(cart *model.Cart) (err error) {
	sqlstr := "update cart set tcount=? , tamout=? where id=?"
	_, err = utils.Db.Exec(sqlstr, cart.GetTcount(), cart.GetTamout(), cart.Id)
	return
}

//清空购物车
func EmptyCart(cartId string) (err error) {
	err = DelCartItemByCartId(cartId)
	sqlstr := "delete from cart where id=?"
	_, err = utils.Db.Exec(sqlstr, cartId)
	return err
}
